# Copyright 2012 Google Inc. All Rights Reserved.

"""One-line documentation for ytapi_helper module.

A detailed description of ytapi_helper.
"""

__author__ = 'pluu@google.com (Phong Luu)'

import gdata.youtube
import gdata.youtube.service
import time
from google.appengine.api import app_identity
from gdata.alt import appengine


class YTApiHelper(object):
  DEV_KEY = ('AI39si6fXrpH0sxfh9Q4jsnAklZXfAaZQB0O9DJ6i6Kw'
             'HUbUDmyMInrRr-oCejRjg8F8noxky9SNAMQ7hoSyxa-RNZUPMVYVMA')
  PLAYLIST_URI = 'http://gdata.youtube.com/feeds/api/playlists/%s'
  BACKOFF_PERIOD = 20

  def __init__(self, oauth_token):
    self.yt_service = gdata.youtube.service.YouTubeService()
    self.yt_service.developer_key = self.DEV_KEY
    self.yt_service.client_id = app_identity.get_application_id()
    self.yt_service.source = 'content-curator-tool'
    self.yt_service.ssl = True
    appengine.run_on_appengine(
        self.yt_service, store_tokens=True,
        single_user_mode=True)
    if oauth_token is not None:
      self.yt_service.SetAuthSubToken(oauth_token)


  def CreateBulkPlaylists(self, name_prefix, quantity):
    for i in xrange(1, quantity + 1):
      time.sleep(self.BACKOFF_PERIOD)
      new_public_playlistentry = yt_service.AddPlaylist(
          '%s %d' % (name_prefix, i),
          'Playlist: %s %d' % (name_prefix, i))

      if isinstance(
          new_public_playlistentry, gdata.youtube.YouTubePlaylistEntry):
        print 'New playlist added'
      else:
        #raise seomthing
        pass
  
  def AddVideoToPlaylist(self, playlistid, videoid):
    playlist_video_entry = self.yt_service.AddPlaylistVideoEntryToPlaylist(
        self.PLAYLIST_URI % playlistid, videoid, '','')

    if isinstance(
        playlist_video_entry, gdata.youtube.YouTubePlaylistVideoEntry):
      return True
    else:
      False

  def GetPlaylistVideos(self, playlistid, start_index=1, result_store={}):
    if start_index == 1:
      result_store = {}
    url = (
        'http://gdata.youtube.com/feeds/api/playlists/%s?start-index=%d&max-results=50')
    url = url % (playlistid, start_index)
    playlist_video_feed = self.yt_service.GetYouTubePlaylistVideoFeed(uri=url)
    total_results = int(playlist_video_feed.total_results.text)
    
    # iterate through the feed as you would with any other
    for playlist_video_entry in playlist_video_feed.entry:
      video_href = playlist_video_entry.link[2].href
      #print '%s --- %s' % (video_href,video_href.split('/')[6])
      result_store.update({
          video_href.split('/')[6]: playlist_video_entry.id.text.split('/')[-1]})
     
    if total_results >= start_index:
      start_index += 50
      return self.GetPlaylistVideos(playlistid, start_index, result_store)
    else:
      return result_store
    
   #return videoid_playlist_entry_map

  def DeleteVideoFromPlaylist(self, playlistid, playlist_entry_id):
    response = self.yt_service.DeletePlaylistVideoEntry(
        self.PLAYLIST_URI % playlistid, playlist_entry_id)
    if response is True:
      return True
    else:
      return False
